package service;

import dto.GameDto;
import entity.GameAct;

import java.awt.*;
import java.util.Random;

public class GameService {
    private Random random = new Random();//随机数生成器
    private GameDto dto;
    private static final int MAX_TYPE = 6;
    public GameService(GameDto dto) {
        this.dto = dto;
        GameAct act = new GameAct(random.nextInt(MAX_TYPE));
        dto.setGameAct(act);
    }



    /**
     * 控制器方向键上//旋转
     */
    public void keyUp() {
       this.dto.getGameAct().round(this.dto.getGameMap());
    }

    /**
     * 控制器方向键下
     */
    public void keyDown() {
        //方块向下移动，并判断是否移动成功
        if (this.dto.getGameAct().move(0,1,this.dto.getGameMap())) {
           return;
        }
        //获得游戏地图对象
        boolean[][] map = this.dto.getGameMap();
        //获得方块对象
        Point[] act = this.dto.getGameAct().getActPoints();

        for (int i = 0; i < act.length; i++) {
            map[act[i].x][act[i].y] = true;
        }
        //创建一个方块

        this.dto.getGameAct().init(this.dto.getNext());
        //随机生成下一个方块
        this.dto.setNext(random.nextInt(MAX_TYPE));

    }

    /**
     * 控制方向键向左
     */
    public void keyLeft() {
        this.dto.getGameAct().move(-1,0,this.dto.getGameMap());
    }

    /**
     * 控制方向键向右
     */
    public void keyRight() {
        this.dto.getGameAct().move(1,0,this.dto.getGameMap());
    }

    /**
     * 边界判定
     * @return
     */
    private boolean canMove(int moveX,int moveY) {
        Point[] nowPoints = this.dto.getGameAct().getActPoints();
        for(int i=0;i<nowPoints.length;i++) {
            int newX = nowPoints[i].x + moveX;
            int newY = nowPoints[i].y + moveY;
            if(newX < 0 || newX > 9 || newY < 0 || newY > 17 ) {
                return  false;
            }
        }
        return true;
    }


}
